from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import base64
import time
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.common.by import By

caps = {
    "platformName": "Android",
    "automationName": "uiautomator2",
    "udid": "127.0.0.1:9618",
    "appPackage": "com.github.kr328.clash",
    "appActivity": "com.github.kr328.clash/.MainActivity",
    "noReset": True,
    "chromedriverExecutable":"/root/chromedriver/chromedriver",
    "autoGrantPermissions": True,
    "uiautomator2ServerLaunchTimeout": 120000,  # 增加服务器启动超时
    "adbExecTimeout": 120000,  # 增加ADB执行超时
}

driver = webdriver.Remote("http://127.0.0.1:4723", caps)

# 启动指定 Activity
driver.start_activity("com.github.kr328.clash", "com.github.kr328.clash/.MainActivity")
#//android.widget.Button[@text="Agree and continue"]

try:
    allow_notify = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
        AppiumBy.XPATH,
        '//android.view.View[@content-desc="添加代理"]'
    )))
    allow_notify.click()
    print("点击添加代理")
    # 等待并处理权限提示框

except (TimeoutException, NoSuchElementException):
    print("没有找到添加代理按钮")
    source = driver.page_source
    print(source)

try:
    # 定位目标 EditText
    element_xpath = ("//android.widget.FrameLayout[@resource-id='android:id/content']"
                     "/android.widget.FrameLayout/android.view.View/android.view.View"
                     "/android.view.View/android.view.View/android.view.View[2]"
                     "/android.widget.EditText[1]")

    elem = driver.find_element("xpath", element_xpath)

    # 检查是否可输入
    if elem.is_enabled() and elem.get_attribute("focusable") == "true":
        elem.click()
        elem.clear()
        elem.send_keys("myproxy1")
        print("✅ 输入成功：myproxy1")
    else:
        print("⚠️ 该文本框不可输入")

except NoSuchElementException:
    print("❌ 未找到该文本框，请检查 XPath 是否正确")
try:
    # 选择的选项，可改为 "http"
    protocol = "http"
    if protocol== "socks5":
        #// android.view.View[ @ content - desc = "socks5"]
        # 用 text 属性定位选项按钮
        xpath = f"//android.view.View[@text='http']/android.widget.Button"
        elem = driver.find_element("xpath", xpath)
        elem.click()

        xpath='//android.view.View[@content-desc="socks5"]'
        elem = driver.find_element("xpath", xpath)
        elem.click()

except NoSuchElementException:
    print(f"❌ 未找到选项: {protocol}")
try:
    # 输入代理地址
    element_xpath = ('//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[2]/android.widget.EditText[2]')
    elem = driver.find_element("xpath", element_xpath)
    if elem.is_enabled() and elem.get_attribute("focusable") == "true":
        elem.click()
        elem.clear()
        elem.send_keys("brd.superproxy.io")
        print("✅ 输入成功：")
    else:
        print("⚠️ 该文本框不可输入")
except:
    print("未找到代理地址输入框")
try:
    # 输入代理端口
    element_xpath = (
        '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[2]/android.widget.EditText[3]')
    elem = driver.find_element("xpath", element_xpath)
    if elem.is_enabled() and elem.get_attribute("focusable") == "true":
        elem.click()
        elem.clear()
        elem.send_keys("33335")
        print("✅ 输入成功：127.0.0.1:1080")
    else:
        print("⚠️ 该文本框不可输入")
except:
    print("未找到代理地址输入框")
try:
    # 输入代理端口
    element_xpath = (
        '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[2]/android.widget.EditText[4]')
    elem = driver.find_element("xpath", element_xpath)
    if elem.is_enabled() and elem.get_attribute("focusable") == "true":
        elem.click()
        elem.clear()
        elem.send_keys("brd-customer-hl_c487dc73-zone-datacenter_proxy1")
        print("✅ 输入成功：127.0.0.1:1080")
    else:
        print("⚠️ 该文本框不可输入")
except:
    print("未找到代理地址输入框")
try:
    # 输入代理端口
    element_xpath = (
        '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[2]/android.widget.EditText[5]')
    elem = driver.find_element("xpath", element_xpath)
    if elem.is_enabled() and elem.get_attribute("focusable") == "true":
        elem.click()
        elem.clear()
        elem.send_keys("h5652dk8kj1r")
        print("✅ 输入成功：127.0.0.1:1080")
    else:
        print("⚠️ 该文本框不可输入")
except:
    print("未找到代理地址输入框")
#//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[1]/android.widget.Button[2]
try:
    save = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
        AppiumBy.XPATH,
        '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View[1]/android.widget.Button[2]'
    )))
    save.click()
    print("点击添加代理")
    # 等待并处理权限提示框
except:
    print("没有找到添加代理按钮")

#brd-customer-hl_c487dc73-zone-datacenter_proxy1


try:
    # 等待整个父列表加载完成
    parent_xpath = '//android.widget.FrameLayout[@resource-id="android:id/content"]/android.widget.FrameLayout/android.view.View/android.view.View/android.view.View/android.view.View/android.view.View'

    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, parent_xpath))
    )

    # 获取父容器下的所有 Switch 元素
    switches = driver.find_elements(By.XPATH, f"{parent_xpath}//android.widget.Switch")

    target_keyword = "brd.superproxy.io:33335"
    found = False

    for switch in switches:
        desc = switch.get_attribute("contentDescription")  # 获取 content-desc 属性
        if target_keyword in desc:
            print(f"✅ 找到匹配的代理: {desc}")
            switch.click()
            found = True
            break

    if not found:
        print(f"⚠️ 未找到包含 {target_keyword} 的代理项")

except TimeoutException:
    print("❌ 等待超时：列表未加载完成")
except Exception as e:
    print(f"⚠️ 出现异常：{e}")
#//android.widget.Button[@resource-id="com.android.permissioncontroller:id/permission_allow_button"]
try:
    allow_notify = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((
        AppiumBy.XPATH,
        '//android.widget.Button[@resource-id="com.android.permissioncontroller:id/permission_allow_button"]'
    )))
    allow_notify.click()
    print("点击allow notification")
    # 等待并处理权限提示框

except (TimeoutException, NoSuchElementException):
    print("没有找到allow notification")
driver.quit()
